# 空哈希
hash1 = {}
hash2 = Hash.new

# 带初始值的哈希
hash3 = { "name" => "Alice", "age" => 25 }
hash4 = { name: "Bob", age: 30 } # 符号键简写
hash5 = Hash[:name, "Charlie", :age, 35]

# 默认值
hash6 = Hash.new("default")
hash7 = Hash.new { |h, k| h[k] = [] } # 复杂默认值

puts hash1 # {}
puts hash2 # {}
puts hash3 # {"name"=>"Alice", "age"=>25}
puts hash4 # {:name=>"Bob", :age=>30}
puts hash5 # {:name=>"Charlie", :age=>35}
puts hash6 # {}
puts hash7 # {}

puts "==============================="

person = { name: "Alice", age: 25 }

# 访问
puts person[:name]      # "Alice"
puts person.fetch(:age) # 25 (安全访问)

# 修改/添加
person[:age] = 26
person[:gender] = "female"

# 检查存在
puts person.key?(:name) # true
puts person.value?("Alice") # true

puts "============================="

user = { name: "Bob", age: 30, city: "New York" }

# 遍历键值对
user.each { |key, value| puts "#{key}: #{value}" }
# 输出：
# name: Bob
# age: 30
# city: New York

# 只遍历键
user.each_key { |key| puts key }
# 输出：
# name
# age
# city

# 只遍历值
user.each_value { |value| puts value }
# 输出：
# Bob
# 30
# New York

puts "================="

h1 = { a: 1, b: 2 }
h2 = { b: 3, c: 4 }

# 合并哈希
puts h1.merge(h2)   # {:a=>1, :b=>3, :c=>4}

# 反转键值
puts h1.invert      # {1=>:a, 2=>:b}

# 转换为数组
puts h1.to_a        # [[:a, 1], [:b, 2]]

puts "========================"

scores = { math: 90, english: 85, science: 92 }

# 筛选
good_scores = scores.select { |k, v| v > 85 }
puts good_scores
# {:math=>90, :science=>92}

# 转换值
updated = scores.transform_values { |v| v + 5 }
puts updated
# {:math=>95, :english=>90, :science=>97}

puts "=========================="

arr = [[:name, "Alice"], [:age, 25]]
hash = arr.to_h
puts hash
# {:name=>"Alice", :age=>25}

puts "================"

a = [1, 2]
b = [*a, 3, 4] # [1, 2, 3, 4]
puts b

puts "=========  哈希参数  =================="

def greet(name:, age:)
  "Hello #{name}, you're #{age} years old"
end

params = { name: "Alice", age: 25 }
puts greet(**params) # Hello Alice, you're 25 years old


%i[red green blue] # [:red, :green, :blue]

# 计算字母频率
freq = Hash.new(0)
"hello".each_char { |c| freq[c] += 1 }
# {"h"=>1, "e"=>1, "l"=>2, "o"=>1}

first, *rest = [1, 2, 3, 4]
# first = 1, rest = [2, 3, 4]